import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import { store } from "../../store/index";
import { Toast } from "antd-mobile";
axios.defaults.baseURL = process.env.baseUrl;
axios.interceptors.request.use(
  (config) => {
    if (config.headers) {
      config.headers["X-Requested-With"] = "XMLHttpRequest";
      const useTokenReducer = store.getState().useTokenReducer;
      if (useTokenReducer.token) {
        config.headers.Authorization = `Bearer ${useTokenReducer.token}`;
      }
      // 如果数据为数组类型则转换为JSON格式
      if (config.data instanceof Array) {
        config.data = JSON.stringify(config.data);
        config.headers["Content-Type"] = "application/json;charset=UTF-8";
      }
    }
    return config;
  },
  (error) => {
    //Message.error('服务器异常，请联系管理员。');
    return Promise.reject(error);
  }
);
axios.interceptors.response.use(
  (response) => {
    if (response.status === 400) {
      Toast.show({
        icon: "fail",
        content: response.data?.message || "请求失败",
      });
    }
    return response;
  },
  (error) => {
    Toast.show({
      icon: "fail",
      content: error.message || "请求失败",
    });
    return Promise.reject(error);
  }
);
export default axios;
